package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ReadService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ReadDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.behavior.ApUserBehaviorDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ReadServiceImpl implements ReadService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 阅读次数
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ApUserBehaviorDto dto) {
//        log.info("==========>{}",dto);
        //校验参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查看线程用户
        ApUser apUser = ApThreadLocalUtil.getApUser();
        //游客登录   结束
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //用户登录   保存
        String result = (String) redisTemplate.opsForHash().get(apUser.getId().toString(),
                        BehaviorConstants.READ_BEHAVIOR+dto.getArticleId());
        if (result!=null){
            ReadDto readDto = JSON.parseObject(result, ReadDto.class);
            Integer count = readDto.getCount();
            count+=dto.getCount();
            dto.setCount(count);
        }
        redisTemplate.opsForHash().put(apUser.getId().toString(),
                BehaviorConstants.READ_BEHAVIOR+dto.getArticleId(), JSON.toJSONString(dto));
        kafkaTemplate.send("read_count",JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
